<?php

namespace app\console\controller;

namespace app\console\controller;

use app\console\model\MemberCardRecords;
use think\Session;
use think\Url;
use think\Cache;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\Ad as AdModel;
use app\console\model\Shop as Model;
use app\common\trilateral\Classify as ClassifyAlias;
use think\Db;
use app\console\model\Single;
class Shop extends Controller
{


    /**
     * 前置方法
     */
    protected $beforeActionList = [
        'shop_list'  =>[]
    ];

    public function shop_list()
    {
        $where = [];
        if(\session('auding_status') == 1){
            $where['id'] = ['eq',\session('shop_id')];
        }
        $shop_list = Db::name('shop s')->field('id,shop_title')->where($where)->select();
        $this->assign('shop_list', $shop_list);
    }


    /**
     * 广告位列表
     */
    public function index($pa = 10)
    {
        $param = Request::instance()->param('','','trim');
        $auding_status = Session::get('auding_status');
        $where = [];
        if($auding_status == 1){
            $where['s.id'] = ['eq',\session('shop_id')];
        }

        if(!empty($param['area_id'])) $where['city_id'] = ['eq',$param['area_id']];
        if(!empty($param['title'])) $where['shop_title'] = ['like','%'.$param['title'].'%'];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode(' / ', $param['interval_timer']);
            $where['s.create_time'] = ['between time', [($interval_timer[0]), ($interval_timer[1])]];
        }
        $data = Model::order('sort','asc')
            ->alias('s')
            ->join('manager m','s.shop_manage_id = m.id','left')
            ->join('area a','s.city_id = a.area_id')
            ->field('s.*,m.username,a.area_name')
            ->order('id','desc')
            ->where($where)
            ->paginate($pa,false,['query' => $param]);
        if(isset($param['export'])){
            $this->push($data,'门店数据导出');
        }
        $list = Db::name('area')->select();
        return $this->fetch('', [
            'data' => $data,
            'list' => $list
        ]);
    }


    public function push($data,$name = '优惠券导出')
    {

        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '当前绑定管理员')
            ->setCellValue('C1', '门店名称')
            ->setCellValue('D1', '店主账号')
            ->setCellValue('E1', '店主姓名')
            ->setCellValue('F1', '创建时间');
        $sheet1 = ['A', 'B', 'C', 'D', 'I'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['id'])
                ->setCellValue('B' . $num, $v['username'])
                ->setCellValue('C' . $num, $v['shop_title'])
                ->setCellValue('D' . $num, $v['shop_phone'])
                ->setCellValue('E' . $num, $v['shop_name'])
                ->setCellValue('F' . $num, $v['create_time']);
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('门店数据导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 门店使用会员卡
     */

    public function card($username = 0){
        if(Request::instance()->isPost()){
            $member_id = Db::name('member')->where('username',$username)->value('id');
            $data = Db::name('member_card')->where('member_id',$member_id)->find();
            if(empty($data)){
                fail('当前会员无会员卡');
            }
        }

        return view('',[]);
    }

    /**
     * @param int $username
     * @return array|mixed|\think\response\View
     * 会员卡
     */
    public function card2($username = 0)
    {
        $param = Request::instance()->param();

        $member_id = Db::name('member')->where('username', $username)->value('id');
        $find = Db::name('member_card')->where('member_id', $member_id)->find();
        if (empty($find)) {
            fail('当前会员无会员卡');
        }
        $data_card = Db::name('member_card mc')
            ->join('member m', 'mc.member_id = m.id')
            ->where('mc.member_id', $member_id)
            ->whereTime('end_time', '>', time())
            ->where('minus_count', 'gt', 0)
            ->where('type', 'gt', 0)
            ->field('mc.*,m.username')
            ->select();//会员list
        return view('', [
            'data' => $data_card]
            );
    }

    /**
     * @param int $username
     * @return array|mixed|\think\response\View
     * 会员卡
     */
    public function member_card($username = 0)
    {
        $param = Request::instance()->param();

        $member_id = Db::name('member')->where('username', $username)->value('id');
        $find = Db::name('member_card')->where('member_id', $member_id)->find();
        if (empty($find)) {
            fail('当前会员无会员卡');
        }

        $data_card = Db::name('member_card mc')
            ->join('member m', 'mc.member_id = m.id')
            ->where('mc.member_id', $member_id)
//            ->whereTime('end_time', '>', time())
//            ->where('minus_count', 'gt', 0)
            ->where('type', 'gt', 0)
            ->field('mc.*,m.username,m.car_number,m.is_certification')
            ->order('end_time','desc')
            ->select();//会员list
        $card_id = Request::instance()->param('card_id');

        $card_array = Db::name('member_card mc')
            ->join('member m', 'mc.member_id = m.id')
            ->where('mc.member_id', $member_id)
            ->field('mc.*,m.username')
            ->column('mc.id');//用于查询会员id记录 当前用户所有会员卡
        if(!isset($card_id)){
            if(!$data_card->isEmpty()){
                $card_id = $data_card[0]['id'];
            }

        }

        //$single = Db::name('single')->order(['sort' => 'asc','id' => 'asc'])->select();
        $single = Single::order(['sort' => 'asc', 'id' => 'asc'])->select();
        // halt($data);


        $single = getMenuTree($single);

        if (Request::instance()->isPost()) {
            $card_type = Db::name('member_card')->where('id', $param['card_id'])->value('type');
            $minus_count = Db::name('member_card')->where('id', $param['card_id'])->value('minus_count');
            $end_time = Db::name('member_card')->where('id', $param['card_id'])->value('end_time');
            if ($minus_count <= 0) {
                fail('次卡使用次数已用光');
            }
            if(strtotime($end_time) < time()){
                fail('会员卡已经过期');
            }
            if (!empty($param['assignor_id']) && count($param['assignor_id']) != count(array_unique($param['assignor_id']))) {
                //fail('服务人员不能重复');
            }
            if(isset($param['single_id']) && count(array_unique($param['single_id'])) >= 2){
                //fail('一次只能服务一个分类');
            }
            if(isset($param['assignor_content']) && count(array_unique($param['assignor_content'])) >= 2){
                //fail('一次只能服务一个分类');
            }
            $count = Db::name('member_card')->where('id', $param['card_id'])->value('count');
            if (empty($param['assignor_id'])) fail('没有添加服务人员');
//            $insert = [
//                'shop_id' => $shop_id,
//                'member_id' => $member_id,
//                'shop_title' => $shop_title,
//                'service_content' => $param['assignor_content'],
//                'card_id' => $param['card_id'],
//                'card_type' => $card_type,
//                'create_time' => date('Y-m-d H:i:s',time())
//                ];


            $shop_assignor_records = [];
            for ($i = 0; $i < count($param['assignor_id']); $i++) {
                if (\session('auding_status') == 1) {
                    $shop_assignor_records[$i]['shop_id'] = \session('shop_id');
                    $shop_assignor_records[$i]['shop_title'] = Db::name('shop')->where('id', \session('shop_id'))->value('shop_title');
                } else {
                    $shop_assignor_records[$i]['shop_id'] = Request::instance()->param()['shop_id'][$i];
                    $shop_assignor_records[$i]['shop_title'] = Db::name('shop')->where('id', Request::instance()->param()['shop_id'][$i])->value('shop_title');
                }
                //$single_id = explode('-',$param['single_id'][0])[0];//门店服务分类 第一个类就代表所有相同的服务类了
                $single_title = Db::name('single')->where('id',$param['single_id'][0])->value('cat_name');//服务类型
                //$assignor_price = explode('-',$param['single_id'][0])[1];//门店金额

                $shop_assignor_records[$i]['member_id'] = $member_id;
                $shop_assignor_records[$i]['username'] = Db::name('member')->where('id',$member_id)->value('username');
                $shop_assignor_records[$i]['shop_assignor_id'] = $param['assignor_id'][$i];
                $shop_assignor_records[$i]['shop_assignor_name'] = Db::name('shop_assignor')->where('id', $param['assignor_id'][$i])->value('name');
                $shop_assignor_records[$i]['service_content'] = $param['assignor_content'][$i];
                $shop_assignor_records[$i]['single_id'] = $param['single_id'][$i];
                $shop_assignor_records[$i]['single_title'] = Db::name('single')->where('id',$param['single_id'][0])->value('cat_name');
                $shop_assignor_records[$i]['price'] = $param['assignor_price'][$i];
                $shop_assignor_records[$i]['card_id'] = $param['card_id'];
                $shop_assignor_records[$i]['card_type'] = $card_type;
                $shop_assignor_records[$i]['is_agree'] = 1;
                if ($card_type == 2) { //次卡
                    //$shop_assignor_records[$i]['minus_count'] = $minus_count - 1;
                    $shop_assignor_records[$i]['count'] = $count;
                    $shop_assignor_records[$i]['minus_count'] = $count;
                }
                $shop_assignor_records[$i]['create_time'] = date('Y-m-d H:i:s', time());
            }
            $records = (new MemberCardRecords())->saveAll($shop_assignor_records);
            $card_title = Db::name('member_card')->where('id',$param['card_id'])->value('title');//会员卡标题
            Db::name('member_message')->insert(
                ['member_id' => $find['member_id'],
                    'order_number' => $records[0]->id,
                    'type_id' => 5,
                    'title' => $card_title.' 会员卡已设置,请确认使用',
                    'content' => '服务类型:'.$single_title,
                    'is_click' => 1,
                    'create_time' => date('Y-m-d H:i:s', time())
                ]);
            (new \app\index\controller\MemberMessage())->jpushMessage($find['member_id'], $card_title.' 会员卡已设置,请确认使用','服务类型:'.$single_title, 5);

            //Db::name('member_card')->where('id', $param['card_id'])->setDec('minus_count');//次卡减去次数
            win('门店人员分配完毕(会员卡)', Url::build('member_card_records'));
        }

        $member_card_records = Db::name('member_card_records')
            ->alias('mcr')
            ->join('member_card mc','mcr.card_id = mc.id','left')
            ->field('mcr.*,mc.title')
            ->where('mcr.card_id', 'in', $card_id)
            ->order('mcr.create_time', 'desc')
            ->select()->toArray();

        if(!empty($member_card_records)){
            foreach ($member_card_records as $k => &$v){ //服务类标题
                $v['single_title1'] = Db::name('single')->where('id',$v['single_id'])->value('cat_name');
                $v['service_content'] = Db::name('single')->where('id',$v['service_content'])->value('cat_name');
            }
        }

        $shop_list = Db::name('shop')->where('is_delete', 1)->where('auding_status', 2)->select();
        if (\session('auding_status') == 1) {
            $shop_id = \session('shop_id');
            $service_people_price = Db::name('shop_service_price')
                ->alias('ssp')
                ->join('single s','ssp.single_id = s.id','left')
                ->where('shop_id',$shop_id)
                ->where('s.parent_id','eq',0)
                ->where('auding_status',2)
                ->where('is_delete',1)
                ->field('s.id,s.cat_name,ssp.person_price')
                ->select(); //服务人员提成;
        } else {
            $shop_id = $shop_list[0]['id'];
            $service_people_price = Db::name('shop_service_price')
                ->alias('ssp')
                ->join('single s','ssp.single_id = s.id','left')
                ->where('s.parent_id','eq',0)
                ->where('shop_id',$shop_list[0]['id'])
                ->where('auding_status',2)
                ->where('is_delete',1)
                ->field('s.id,s.cat_name,ssp.person_price')
                ->select(); //服务人员提成;
        }
        $shop_assignor = Db::name('shop_assignor')->where('shop_id', $shop_id)->select();


        //if(empty($shop_id)) $shop_id = $shop_list[3]['id'];
        $shop_title = Db::name('shop')->where('id',$shop_id)->value('shop_title');
        $where = [];
        if (!empty($param['title'])) $where['cat_name'] = ['like', '%' . $param['title'] . '%'];
        $now_gift_count = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])
            ->where($where)
            ->where('parent_id','neq',0)
            ->select(); //服务种类 门店金额
        if (!empty($now_gift_count)) {
            foreach ($now_gift_count as $k => &$v) {
                $v['price'] = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $v['id'])->value('price');
                $v['person_price'] = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $v['id'])->value('person_price');
            }
        }

        $service_people_price2 = Db::name('shop_service_price')
            ->alias('ssp')
            ->join('single s','ssp.single_id = s.id','right')
            ->where('shop_id',$shop_id)
            ->where('s.parent_id','eq',$service_people_price[0]['id'])
            ->where('auding_status',2)
            ->where('is_delete',1)
            ->field('s.id,s.cat_name,ssp.person_price')
            ->select(); //服务人员提成;

        return view('', [
            'shop_list' => $shop_list,
            'data' => $data_card,
            'now_gift_count' => $now_gift_count,
            'news_type' => $single,
            'member_card_records' => $member_card_records,
            'service_people_price' => json_encode($service_people_price),
            'service_people_price2' => json_encode($service_people_price2),
            'shop_assignor' => $shop_assignor]);
    }

    /**
     * @param $shop_id
     * @return false|\PDOStatement|string|\think\Collection
     * 会员卡服务金额
     */
    public function card_service_price($shop_id){
        $now_gift_count = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])
            ->where('parent_id','eq',0)
            ->select();
        if (!empty($now_gift_count)) {
            foreach ($now_gift_count as $k => &$v) {
                $v['price'] = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $v['id'])->value('price');
                $v['person_price'] = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $v['id'])->value('person_price');
            }
        }
        return $now_gift_count;
    }

    /**
     * 会员卡记录
     */
    public function member_card_records($pages = 10)
    {
        //$mc_shop_id0 = Db::name('member_card')->where('')->column('');
        $param = Request::instance()->param();
        $where = [];
        if(\session('auding_status') == 1){
            $where['mcr.shop_id'] = ['eq',\session('shop_id')];
        }else{

        }
        if (!empty($param['title'])) $where['mcr.username|mc.id|sa.name'] = ['like','%'.$param['title'].'%'];
        if (!empty($param['shop_id'])) $where['mcr.shop_id'] = ['eq', $param['shop_id']];
        if (!empty($param['single_id'])) $where['mcr.single_id'] = ['eq', $param['single_id']];
        if (!empty($param['is_agree'])) $where['mcr.is_agree'] = ['eq', $param['is_agree']];
        if (!empty($param['card_type'])) $where['mcr.card_type'] = ['eq', $param['card_type']];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['mcr.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        $data = (new MemberCardRecords())
            ->alias('mcr')
            ->join('member_card mc','mc.id = mcr.card_id','left')
            ->join('member m','m.id = mcr.member_id','left')
            ->join('shop_assignor sa','mcr.shop_assignor_id = sa.id','left')
            ->field('mcr.*,m.car_number,m.is_certification,sa.*,mcr.create_time,mc.order_id')
            ->where($where)
            ->order('mcr.create_time','desc')
            ->paginate($pages,false,['query' => $param])->each(function($item,$key){
                $item->c = '无';
                if(session('role_id') != 1){
                    $item->username = hideStr($item->username,1,6);
                }
                switch ($item->is_certification){
                    case 1:
                        $item->is_certification_text = '未认证';
                    break;
                    case 2:
                        $item->is_certification_text = '已认证';
                    break;
                    case 3:
                        $item->is_certification_text = '等待认证';
                    break;
                    default:
                        $item->is_certification_text = '-';
                        break;
                }
                $item->single_id = Db::name('single')->where('id',$item->single_id)->value('cat_name');
                $item->service_content = Db::name('single')->where('id',$item->service_content)->value('cat_name');
                if($item->is_agree == 1){
                    $item->is_agree = '未同意';
                }else{
                    $item->is_agree = '已同意';
                }
                switch ($item->card_type){
                    case 1;
                        $item->c = '无次数限制';
                        $item->card_type = '年卡';
                    break;
                    case 2;
                        $item->c = $item->count.'('.$item->minus_count.')';
                        $item->card_type = '次卡';
                        break;
                }
            });

        $param = Request::instance()->param();
        if (isset($param['export'])) {
            $this->push_coupon($data);
        }
        $number = (new MemberCardRecords())
            ->alias('mcr')
            ->join('member_card mc','mc.id = mcr.card_id','left')
            ->join('member m','m.id = mcr.member_id','left')
            ->join('shop_assignor sa','mcr.shop_assignor_id = sa.id','left')
            ->field('mcr.*')
            ->where($where)
            ->group('create_time')
            ->order('mcr.create_time','desc')->count();
        $m_data_price = (new MemberCardRecords())
            ->alias('mcr')
            ->join('member_card mc','mc.id = mcr.card_id','left')
            ->join('member m','m.id = mcr.member_id','left')
            ->join('shop_assignor sa','mcr.shop_assignor_id = sa.id','left')
            ->field('mcr.*')
            ->where($where)
           // ->group('mcr.create_time')
            ->order('mcr.create_time','asc')->select();

        $price = 0;
        if(!empty($m_data_price)){
            foreach ($m_data_price as &$v){
                $price +=$v['price'];
            }
        }
        return view('', ['data' => $data,'number' => $number,'price' => $price]);
    }

    public function mc_table($id){
        $data =
            Db::name('order')
                ->alias('o')
                ->join('member m','o.member_id = m.id')
                ->join('member_card mc','o.id = mc.order_id')
                ->join('member_card_records mcr','mc.id = mcr.card_id')
                ->join('shop_assignor sa','sa.id = mcr.shop_assignor_id')
                ->field('o.*,m.car_number,m.id_code,m.brand_number,sa.name,mcr.price,mcr.service_content,mc.title,mcr.single_id')
                ->where('o.id',$id)
                ->find();
        $data['cat_name'] = Db::name('single')->where('id',$data['single_id'])->value('cat_name');
        $data['one_cat'] = Db::name('single')->where('id',$data['service_content'])->value('cat_name');

        return view('mc_table',['item' => $data,'shop_assignor_records' => []]);
    }

    /**
     * 会员卡记录
     */
    public function member_card_recordscw($pages = 10)
    {
        //$mc_shop_id0 = Db::name('member_card')->where('')->column('');
        $param = Request::instance()->param();
        $where = [];
        if(\session('auding_status') == 1){
            $where['mcr.shop_id'] = ['eq',\session('shop_id')];
        }else{

        }
        if (!empty($param['title'])) $where['m.username|mc.id|sa.name'] = ['like','%'.$param['title'].'%'];
        if (!empty($param['shop_id'])) $where['mcr.shop_id'] = ['eq', $param['shop_id']];
        if (!empty($param['single_id'])) $where['mcr.single_id'] = ['eq', $param['single_id']];
        if (!empty($param['is_agree'])) $where['mcr.is_agree'] = ['eq', $param['is_agree']];
        if (!empty($param['card_type'])) $where['mcr.card_type'] = ['eq', $param['card_type']];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode('/', $param['interval_timer']);
            $where['mcr.create_time'] = ['between', [$interval_timer[0], $interval_timer[1]]];
        }
        $data = (new MemberCardRecords())
            ->alias('mcr')
            ->join('member_card mc','mc.id = mcr.card_id','left')
            ->join('member m','m.id = mcr.member_id','left')
            ->join('shop_assignor sa','mcr.shop_assignor_id = sa.id','left')
            ->field('mcr.*,m.car_number,m.is_certification,sa.*,mcr.create_time,mc.order_id')
            ->where($where)
            ->order('mcr.create_time','desc')
            ->paginate($pages,false,['query' => $param])->each(function($item,$key){
                $item->c = '无';
                if(session('role_id') != 1){
                    $item->username = hideStr($item->username,1,6);
                }
                switch ($item->is_certification){
                    case 1:
                        $item->is_certification_text = '未认证';
                        break;
                    case 2:
                        $item->is_certification_text = '已认证';
                        break;
                    case 3:
                        $item->is_certification_text = '等待认证';
                        break;
                    default:
                        $item->is_certification_text = '-';
                        break;
                }
                $item->single_id = Db::name('single')->where('id',$item->single_id)->value('cat_name');
                $item->service_content = Db::name('single')->where('id',$item->service_content)->value('cat_name');
                if($item->is_agree == 1){
                    $item->is_agree = '未同意';
                }else{
                    $item->is_agree = '已同意';
                }
                switch ($item->card_type){
                    case 1;
                        $item->c = '无次数限制';
                        $item->card_type = '年卡';
                        break;
                    case 2;
                        $item->c = $item->count.'('.$item->minus_count.')';
                        $item->card_type = '次卡';
                        break;
                }
            });

        $param = Request::instance()->param();
        if (isset($param['export'])) {
            $this->push_coupon($data);
        }
        $number = (new MemberCardRecords())
            ->alias('mcr')
            ->join('member_card mc','mc.id = mcr.card_id','left')
            ->join('member m','m.id = mcr.member_id','left')
            ->join('shop_assignor sa','mcr.shop_assignor_id = sa.id','left')
            ->field('mcr.*')
            ->where($where)
            ->group('create_time')
            ->order('mcr.create_time','desc')->count();
        $m_data_price = (new MemberCardRecords())
            ->alias('mcr')
            ->join('member_card mc','mc.id = mcr.card_id','left')
            ->join('member m','m.id = mcr.member_id','left')
            ->join('shop_assignor sa','mcr.shop_assignor_id = sa.id','left')
            ->field('mcr.*')
            ->where($where)
            // ->group('mcr.create_time')
            ->order('mcr.create_time','asc')->select();
        $price = 0;
        if(!empty($m_data_price)){
            foreach ($m_data_price as &$v){
                $price +=$v['price'];
            }
        }
        return view('shop_member_card_records', ['data' => $data,'number' => $number,'price' => $price]);
    }

    public function daochu(){

    }


    public function push_coupon($data,$name = '会员卡使用记录')
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', '会员卡ID')
            ->setCellValue('B1', '用户名称')
            ->setCellValue('C1', '车牌号')
            ->setCellValue('D1', '是否认证')
            ->setCellValue('E1', '会员卡类型')
            ->setCellValue('F1', '总次数-剩余次数')
            ->setCellValue('G1', '消费门店')
            ->setCellValue('H1', '服务人员')
            ->setCellValue('I1', '服务提成')
            ->setCellValue('J1', '服务分类')
            ->setCellValue('K1', '服务内容')
            ->setCellValue('L1', '是否同意')
            ->setCellValue('M1', '服务时间')
        ;
        $sheet1 = [];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, $v['card_id'])
                ->setCellValue('B' . $num, "\t".$v['username']."\t")
                ->setCellValue('C' . $num, $v['car_number'])
                ->setCellValue('D' . $num, $v['is_certification_text'])
                ->setCellValue('E' . $num, $v['card_type'])
                ->setCellValue('F' . $num, $v['c'])
                ->setCellValue('G' . $num, $v['shop_title'])
                ->setCellValue('H' . $num, "\t".$v['shop_assignor_name']."\t")
                ->setCellValue('I' . $num, $v['price'])
                ->setCellValue('J' . $num, $v['single_id'])
                ->setCellValue('K' . $num, $v['service_content'])
                ->setCellValue('L' . $num, $v['is_agree'])
                ->setCellValue('M' . $num, $v['create_time'])
            ;

            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('会员卡使用记录');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }


    public function now_status(){
        $where=[];
        $auding_status = Session::get('auding_status');//
        if($auding_status == 1){    //如何审核状态是1那就是未通过
            $where['id'] = ['eq',session('shop_id')];
        }
        $data = Model::where($where)->find();
        if(Request::instance()->isPost()){
            $param = Request::instance()->param();
            $ret = (new Model())->allowField(true)->save($param,['id' => $data['id']]);
            if($ret !== false){
                win('操作成功', Url::build('now_status'));
            }
            fail('操作失败');
        }

        return view('shop_status',['info' => $data]);
    }


    /**
     * 广告位创建
     */
    public function create(Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();
            $find = Db::name('shop')
                ->where('shop_manage_id',$data['shop_manage_id'])
                ->where('is_delete',1)
                ->find();
            if($find){
                fail('已被 '.$find['shop_title'].' 绑定');
            }
//            // 验证
//            $validate = Loader::validate('AdType');
//            if (!$validate->scene('create')->check($data)) fail($validate->getError());
            $manage_id = Db::name('manager')->where('id',Session::get('manage_id'))->value('level');
            $auding_status = Db::name('auth_group')->where('id',$manage_id)->value('auding_status');//默认1没有审核权限
            $create_id = Db::name('shop_create')->where('manage_id',Session::get('manage_id'))->find();
            if($auding_status == 1 && !empty($create_id)){
                fail('门店商家只能创建一个门店');
            }

            // 提交数据
            $dispose = $model->allowField(true)->save($data);

            if ($dispose) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }
        $shop_manage = Db::name('manager')->where('level',5)->select();

        return $this->fetch('create', [
            'shop_manage' => $shop_manage,
        ]);

    }


    /**
     * 广告位编辑
     */
    public function update($id, Request $request, Model $model)
    {

        if ($request->instance()->isPost()) {

            $data = $request->instance()->param();
            $find = Db::name('shop')
                ->where('shop_manage_id',$data['shop_manage_id'])
                ->where('id','neq',$id)
                ->where('is_delete',1)
                ->find();
            if($find){
                fail('已被 '.$find['shop_title'].' 绑定');
            }

            // 验证
           // $validate = Loader::validate('AdType');
           // if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = $model->allowField(true)->save($data, ['id' => $id]);


            if ($dispose !== false) {
                win('操作成功', Url::build('index'));
            }

            fail('操作失败');

        }

        $item = Model::get($id);
        $shop_manage = Db::name('manager')->where('level',5)->select();

        $pic = qrcode('http://lihai.xmdonkey.com/index.php/mobile/user_port/shop_member/shop_id/'.$id,'/shop/'.$id.'.png');
        return $this->fetch('create', [
            'shop_manage' => $shop_manage,
            'item' => $item,
            'pic' => $pic
        ]);
    }



    /**
     * 广告位删除
     */
    public function destroy($id, Model $model)
    {

        if (Request::instance()->isGet()) {
            auding_status($id,'shop_title');
            win('操作成功', Url::build('index'));
        }
        fail('操作失败');

    }
    /**
     * 栏目状态改变
     */
    public function status($id, Request $request, Model $model)
    {
        $id = $request->instance()->param('id');

        $status = $model->where('id', $id)->value('status') == '1' ? 2 : 1;

        if ($model->where('id', $id)->update(['status' => $status])) {
            return $status;
        }
        return false;
    }


    /**
     * 栏目全部删除
     */
    public function destroyAll($id, AdTypeModel $adType)
    {

        if ($adType->amputateAll($id)) {

            win('操作成功', Url::build('AdType/index'));
        }

        fail('操作失败');

    }

    /**
     * @return array|mixed|\think\response\View
     * 服务金额以及人员提成
     */
    public function first_servicePrice()
    {
        $data = Model::order('sort', 'asc')
            ->alias('s')
            ->join('manager m', 's.shop_manage_id = m.id')
            ->join('area a', 's.city_id = a.area_id')
            ->field('s.*,m.username,a.area_name')
            ->order('id', 'desc')
            ->select();
        return view('', ['data' => $data]);
    }

    /**
     * 门店服务金额
     */
    public function servicePrice()
    {
        $param = Request::instance()->param();
        $shop_id = Request::instance()->param('shop_id');
        $shop_title = Db::name('shop')->where('id',$shop_id)->value('shop_title');
        $where = [];
        if (!empty($param['title'])) $where['cat_name'] = ['like', '%' . $param['title'] . '%'];
        $data = \app\console\model\Single::order(['sort' => 'asc', 'id' => 'asc'])
            ->where($where)
            ->select();
        if (!empty($data)) {
            foreach ($data as $k => &$v) {
                $v['price'] = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $v['id'])->value('price');
                $v['sj'] = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $v['id'])->value('sj');
                $v['person_price'] = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $v['id'])->value('person_price');
            }
        }
        // halt($data);
        $data = getMenuTree($data);
        if (Request::instance()->isPost()) {
            if (\session('auding_status') == 2) {

            } else {
                $shop_id = \session('shop_id');
            }

        }

        return view('', ['data' => $data,'shop_title' =>$shop_title]);
    }

    /**
     * 门店服务金额
     */
    public function servicePriceUpdate()
    {
        $shop_id = input('shop_id');
        $param = Request::instance()->param()['input'];
        $param2 = Request::instance()->param()['input2'];
        $param3 = Request::instance()->param()['input3'];
        if (!empty($param)) {
            $ret = false;
            foreach ($param as $k => $v) {
                $find = Db::name('shop_service_price')->where('single_id', $k)->where('shop_id', $shop_id)->find();
                if($find){ //存在就是修改
                    $ret = Db::name('shop_service_price')->where('single_id', $k)->where('shop_id', $shop_id)->update(['price' => $v,'person_price' => $param2[$k],'sj' => $param3[$k]]);
                }else{
                    $ret = Db::name('shop_service_price')->insert([
                        'shop_id' => $shop_id,
                        'single_id' => $k,
                        'price' => $v,
                        'sj' => $param3[$k],
                        'person_price' => $param2[$k],
                        'create_time' => date('Y-m-d H:i:s',time())
                    ]);
                }

            }
            if ($ret !== false) {
                win('门店服务金额设置完毕', Url::build('servicePrice',['shop_id' => $shop_id]));
            }
        }
    }





    /*
    * 排列顺序
    */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        foreach ($id as $key => $value) {
            (new AdTypeModel)->where('id', $value)->update(['sort' => $sort[$key]]);
        }

        win('操作成功', Url::build('AdType/index'));
    }

    /**
     * 清除缓存
     */
    protected function clearCache()
    {
        Cache::rm('AdType');
    }
}